package ywpt.web.action.people;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.ecside.table.limit.Limit;
import org.ecside.util.RequestUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import ywpt.core.SystemMessage;
import ywpt.core.web.BaseAction;
import ywpt.model.PeopleScans;
import ywpt.service.people.PeopleScansService;
import ywpt.service.people.PeopleService;
import ywpt.web.common.CommonDictionary;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class PeopleScanAction extends BaseAction implements
ModelDriven<PeopleScans>, Preparable{

	/**
	 * 人事附件相关Action
	 */
	private static final long serialVersionUID = 620035307244261970L;
	private static final int DEFAULT_PAGE_SIZE = 20;
	private static final String URL="/peopleScans/";
	private Long id;
	private Long peopleId;
	private PeopleScans peopleScans;
	private List<PeopleScans> peopleScansList = new ArrayList<PeopleScans>();
	private PeopleScansService  peopleScansService;
	private PeopleService peopleService;
	
	// 文件的上传
	private File[] upload;// 实际上传文件
	private String[] uploadFileName; // 上传文件名
	private String[] uploadContentType; // 文件的内容类型	

	//文件的下载
	private String fileName;
	private String fileRealName;


	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public PeopleScans getPeopleScans() {
		return peopleScans;
	}

	public void setPeopleScans(PeopleScans peopleScans) {
		this.peopleScans = peopleScans;
	}

	public List<PeopleScans> getPeopleScansList() {
		return peopleScansList;
	}

	public void setPeopleScansList(List<PeopleScans> peopleScansList) {
		this.peopleScansList = peopleScansList;
	}

	public PeopleScansService getPeopleScansService() {
		return peopleScansService;
	}

	public void setPeopleScansService(PeopleScansService peopleScansService) {
		this.peopleScansService = peopleScansService;
	}
	public Long getPeopleId() {
		return peopleId;
	}

	public void setPeopleId(Long peopleId) {
		this.peopleId = peopleId;
	}
	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String[] getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}	
	public PeopleService getPeopleService() {
		return peopleService;
	}

	public void setPeopleService(PeopleService peopleService) {
		this.peopleService = peopleService;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFileRealName() {
		return fileRealName;
	}

	public void setFileRealName(String fileRealName) {
		this.fileRealName = fileRealName;
	}	
	
//***************************************************************************
	@Override
	public PeopleScans getModel() {
		return this.peopleScans;
	}

	@Override
	public void prepare() throws Exception {
		if(id != null){
			this.peopleScans = this.peopleScansService.getPeopleScanById(id);
		}else{
			this.peopleScans = new PeopleScans();
		}
	}
	//****************************************************************
	/**
	 *得到附件列表 
	 */
	public String list() throws Exception{
		System.out.println("peopleId 111= " +peopleId);
		DetachedCriteria query = DetachedCriteria.forClass(PeopleScans.class);
		query.createAlias("people", "people").add(Restrictions.eq("people.id", peopleId));
		int totalRows = RequestUtils.getTotalRowsFromRequest(getRequest());
		if (totalRows < 0) {
			totalRows = peopleScansService.getPeopleScansCountByCriteria(query);
		}
		int[] rowStartEnd = RequestUtils.getRowStartEnd(getRequest(),
				totalRows, DEFAULT_PAGE_SIZE, 0);
		Limit limit = RequestUtils.getLimit(getRequest(), "ec", totalRows,
				DEFAULT_PAGE_SIZE);
		int pageSize = limit.getCurrentRowsDisplayed();
		query.addOrder(Order.asc("id"));
		query.setProjection(null);
		peopleScansList.addAll(peopleScansService.getPeopleScans(query, pageSize,
				rowStartEnd[0]));
		getRequest().setAttribute("PAYMETHOD_MAP", CommonDictionary.PAYMETHOD);
		return SUCCESS;
	}
	
	
	public String delete() {
		if (id==null) {
			this.addActionMessage(SystemMessage.NO_OBJECT);
		} else {
			this.peopleScansService.removePeopleScanById(id);
		}
		return SUCCESS;
		
	}
	
	
	
	
	/**
	 *上传人事的附件 
	 */
	public String peopleScanUpload() throws Exception {
		System.out.println("peopleId = " +peopleId);
		try {
			String url = ServletActionContext.getServletContext().getRealPath(URL);
				File file_date = new File(url);
				if(!file_date.exists()){
					file_date.mkdirs();
				}	
			for (int i = 0; i < upload.length; i++) {
				if(upload[i].exists()){
					String type = uploadContentType[i]; // 文件的内容类型
					String fileName = uploadFileName[i];
					String realName = UUID.randomUUID().toString() + getExt(fileName);
					File target = new File(url, realName);
					FileUtils.copyFile(upload[i], target);
					
					PeopleScans ps = new  PeopleScans();
					ps.setPeople(this.peopleService.getPeopleInfoById(peopleId));
					ps.setFileName(fileName);
					ps.setContentType(type);
					ps.setRealName(realName);
					this.peopleScansService.savePeopleScans(ps);
				}
			}
			this.addActionMessage("附件已保存!");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			this.addActionError("保存错误:" + e.getMessage());
			return SUCCESS;
		}
	}	
	
	public static String getExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}	
	
	
	/**
	 *下載人事的附件 
	 */
	public String peopleScanDownload(){
		return SUCCESS;
	}
	
	public void setFileName()
	{
		// 得到请求下载的文件名
		peopleScans = this.peopleScansService.getPeopleScanById(id);
		this.fileName = peopleScans.getRealName(); //uuid的名字
		this.fileRealName = peopleScans.getFileName();//文件上传的时候的原来的名字
	}

	/*
	 * @getFileName 此方法对应的是struts.xml文件中的： 
	 * <param name="contentDisposition">attachment;filename="${fileName}"</param>
	 * 这个属性设置的是下载工具下载文件时显示的文件名， 要想正确的显示中文文件名，我们需要对fileName再次编码
	 * 否则中文名文件将出现乱码，或无法下载的情况
	 */
	public String getDownloadFileName() throws Exception
	{
		return new String(fileRealName.getBytes( ),"ISO-8859-1");
	}

	/*
	 * @getDownloadFile 此方法对应的是struts.xml文件中的： <param
	 * name="inputName">downloadFile</param> 返回下载文件的流，可以参看struts2的源码
	 */
	public InputStream getDownloadFile()
	{

		this.setFileName();
		return ServletActionContext.getServletContext().getResourceAsStream(URL + fileName);
	}


	
	

}
